//
//  BTEDateAlertViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/18.
//

import UIKit

class BTEDateAlertViewController: BTEAlertViewController {
    
    let backgroundImageView = UIImageView(image: UIImage(named: "Group efweew1171277256"))
    
    private let titleLabel = UILabel()
    
    var selectedDay: Int = 1
    var selectedMonth: Int = 1
    var selectedYear: Int = 2024
    
    let days = Array(1...31)
    let months = Array(1...12)
    let years = Array(1900...2100)
    
    let pickerView = UIPickerView()
    
    var onDateSelected: ((String?) -> ())?
    
    let headerLabelContainer = UIView()
    let dayLabel = UILabel()
    let monthLabel = UILabel()
    let yearLabel = UILabel()
    
    init(selectedDay: Int, selectedMonth: Int, selectedYear: Int, onDateSelected: ((String?) -> Void)? = nil) {
        self.selectedDay = selectedDay
        self.selectedMonth = selectedMonth
        self.selectedYear = selectedYear
        self.onDateSelected = onDateSelected
        
        super.init(nibName: nil, bundle: nil)
        
        setupUI()
        
        backgroundImageView.isUserInteractionEnabled = true
        
        pickerView.delegate = self
        pickerView.dataSource = self
        pickerView.translatesAutoresizingMaskIntoConstraints = false
        
        if let dayIndex = days.firstIndex(of: selectedDay),
           let monthIndex = months.firstIndex(of: selectedMonth),
           let yearIndex = years.firstIndex(of: selectedYear) {
            pickerView.selectRow(dayIndex, inComponent: 0, animated: false)
            pickerView.selectRow(monthIndex-1, inComponent: 1, animated: false)
            pickerView.selectRow(yearIndex, inComponent: 2, animated: false)
        }
    }
    
   required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    
    // MARK: - Setup UI
    private func setupUI() {
        mainv.addSubview(backgroundImageView)
        backgroundImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.equalTo((UIScreen.main.bounds.width - 34) * backgroundImageView.frame.height / backgroundImageView.frame.width)
        }
        
        titleLabel.textColor = .colorWithHex("#082252")
        titleLabel.font = .systemFont(ofSize: 18, weight: .bold)
        titleLabel.textAlignment = .center
        titleLabel.text = BTELanguageManager.shared.localizedString(forKey: "Date Selection")
        mainv.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(38)
            make.top.equalToSuperview().offset(44)
        }
        
        backgroundImageView.addSubview(headerLabelContainer)
        headerLabelContainer.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(22)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.height.equalTo(44)
        }
        
        setupDateComponentLabels()
        
        backgroundImageView.addSubview(pickerView)
        pickerView.backgroundColor = .clear
        pickerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(22)
            make.top.equalTo(headerLabelContainer.snp.bottom).offset(-30)
            make.bottom.equalToSuperview().offset(-30)
        }
    }
    
    private func setupDateComponentLabels() {
        headerLabelContainer.addSubview(dayLabel)
        headerLabelContainer.addSubview(monthLabel)
        headerLabelContainer.addSubview(yearLabel)
        
        [dayLabel, monthLabel, yearLabel].forEach {
            $0.textAlignment = .center
            $0.font = .systemFont(ofSize: 16, weight: .bold)
            $0.textColor = .black
        }
        
        dayLabel.text = BTELanguageManager.shared.localizedString(forKey: "Day")
        monthLabel.text = BTELanguageManager.shared.localizedString(forKey: "Month")
        yearLabel.text = BTELanguageManager.shared.localizedString(forKey: "Years")
        
        dayLabel.snp.makeConstraints { make in
            make.top.left.bottom.equalToSuperview()
            make.width.equalTo(headerLabelContainer.snp.width).multipliedBy(1.0 / 3.0)
        }
        
        monthLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(dayLabel.snp.right)
            make.width.equalTo(headerLabelContainer.snp.width).multipliedBy(1.0 / 3.0)
        }
        
        yearLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(monthLabel.snp.right)
            make.width.equalTo(headerLabelContainer.snp.width).multipliedBy(1.0 / 3.0)
        }
    }
    
    // MARK: - Handle confirm action
    override func dosomething() {
        handleDateSelection()
    }
    
    private func handleDateSelection() {
        let selectedDateString = "\(selectedMonth)/\(selectedDay)/\(selectedYear)"
        print(selectedDateString)
        onDateSelected?(selectedDateString)
    }
}

// MARK: - UIPickerView DataSource & Delegate
extension BTEDateAlertViewController: UIPickerViewDataSource, UIPickerViewDelegate {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 0: return days.count
        case 1: return months.count
        case 2: return years.count
        default: return 0
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch component {
        case 0: return "\(days[row])"
        case 1: return "\(months[row])"
        case 2: return "\(years[row])"
        default: return nil
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch component {
        case 0: selectedDay = days[row]
        case 1: selectedMonth = months[row]
        case 2: selectedYear = years[row]
        default: break
        }
    }
    
    // MARK: - Custom row view for styling
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 20)
        
        // Custom highlight styling (if any)
        if let subviewCache = pickerView.subviews.first?.value(forKey: "subviewCache") as? [UIView],
           let middleContainerView = subviewCache.first?.value(forKey: "middleContainerView") as? UIView {
            middleContainerView.backgroundColor = UIColor.colorWithHex("#FFFBF2")!
            middleContainerView.roundCorners(.allCorners, radius: 18)
            middleContainerView.layer.borderWidth = 2
            middleContainerView.layer.borderColor = UIColor.colorWithHex("#082252")!.cgColor
        }
        
        switch component {
        case 0: label.text = "\(days[row])"
        case 1: label.text = "\(months[row])"
        case 2: label.text = "\(years[row])"
        default: break
        }
        
        return label
    }
}
